package com.fanrui.code.gate.core;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import io.netty.channel.Channel;

/**
 * session管理器
 * */
public class SessionManager {
	private ConcurrentMap<Long, PlayerSession> sessions = new ConcurrentHashMap<Long, PlayerSession>();
	/**
	 * 放入新Session，返回旧Session
	 * 
	 * @param session
	 * @return
	 */
	public PlayerSession put(PlayerSession session) {
		Long playerId = session.getPlayerId();
		PlayerSession oldSession = this.sessions.put(playerId, session);
		return oldSession; // 若有重复登陆的，老Session交给外层处理。
	}

	public PlayerSession remove(Long playerId) {
		return this.sessions.remove(playerId);
	}

	public PlayerSession remove(PlayerSession session) {
		return this.sessions.remove(session.getPlayerId());
	}

	public PlayerSession remove(Channel channel) {
		Long playerId = PlayerSession.getPlayerId(channel);
		if (null == playerId) {
			return null;
		} else {
			return this.sessions.remove(playerId);
		}
	}

	public PlayerSession get(Long playerId) {
		return this.sessions.get(playerId);
	}

	public PlayerSession get(PlayerSession session) {
		return this.sessions.get(session.getPlayerId());
	}

	public PlayerSession get(Channel channel) {
		Long playerId = PlayerSession.getPlayerId(channel);
		if (null == playerId) {
			return null;
		} else {
			return this.sessions.get(playerId);
		}
	}

	public Collection<PlayerSession> allSessions() {
		return sessions.values();
	}

}
